<template>
	<BackgroundImage>
		<div class="content">
		<!-- 用户信息头部 -->
		<div class="user-header">
			<div class="user-info">
				<image class="avatar" :src="userStore.avatar || '/static/default-avatar.png'" mode="aspectFill" />
				<div class="user-details">
					<text class="nickname">{{ userStore.nickname || '未登录' }}</text>
					<text class="phone">{{ userStore.phone || '请先登录' }}</text>
				</div>
			</div>
			<button class="logout-btn" @click="handleLogout" v-if="userStore.isLoggedIn">退出登录</button>
			<button class="login-btn" @click="goToLogin" v-else>去登录</button>
		</div>

		<!-- 赛事查询入口 -->
		<div class="match-query-section" v-if="userStore.isLoggedIn">
			<div class="card flex">
				<div class="title">赛事业务查询：</div>
				<button @click="goToMatchQuery" class="match-query-btn">赛事查询</button>
			</div>
		</div>

		<!-- WebSocket测试入口 -->
		<div class="websocket-test-section" v-if="userStore.isLoggedIn">
			<div class="card flex">
				<div class="title">WebSocket测试：</div>
				<button @click="goToWebSocketExample" class="websocket-test-btn">WebSocket测试</button>
			</div>
		</div>

	
		<div class="main">
			<div class="card flex">
				<div class="title">连接魔方：</div>
				<button @click="bleShowScan">连接设备</button>
				<button @click="bleDisconnect">断开设备</button>
			</div>
			
			<div class="card">
				<div class="title">设备信息：</div>
				<code>
					<template v-if="equipment.length">
						设备名：{{ equipment.filter(v => v.model)[0]?.model }},
						版本：{{ equipment.filter(v => v.version)[0]?.version }}
						电量：{{ battery.batteryPower }}
					</template>
				</code>
			</div>
			
			<div class="card flex blank">
				<div class="title">重置魔方至复原状态：</div>
				<button @click="cubeReset">重置魔方</button>
			</div>
	
		
			<div class="viewBox">
				<!-- <Gyroscope /> -->
				<div class="card cube-box">
					<div class="cube3d"></div>
				</div>
			
			</div>
			
			
			<div class="card">
				<div class="c-box flex">
					<div class="title">JSON数据测试</div>
					<button @click="sendJSONData()">发送</button>
				</div>
				<div class="c-box">
					<textarea v-model="json_data_send" placeholder="例如获取设备电量, 可输入: {&quot;adress&quot;: &quot;&quot;,&quot;data&quot;:{&quot;protoId&quot;: 4}}"></textarea>
				</div>
				<div class="c-box">
					<div class="input-box flex">
						<div class="label">protoId筛选：</div>
						<div class="input">
							<input type="text" v-model="json_data_type" placeholder="请输入protoId, 如:4" />
						</div>
					</div>
					
					<button @click="clearHistory">clear</button>
					<code class="text-wrapper">{{ json_data_receive_array.slice(-500).join('\r\n') }}</code>
				</div>
			</div>
			
		</div>
		</div>
	</BackgroundImage>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch,
		watchEffect,
	} from 'vue';

	import {
		mCall,
		mBus
	} from '@/utils/mCall.js'
	import {
		CubeMap,
		formatTime,
		formatDate,
		mergeMove,
	} from '@/utils/common.js'
	import VConsole from 'vconsole'
	import FormulaDisplay from "@/components/FormulaDisplay.vue";
	import Cube from "@/components/Cube.vue";
	import Gyroscope from "@/components/Gyroscope.vue";
	import BackgroundImage from "@/components/BackgroundImage.vue";
	import {
		useCubeStore
	} from "@/stores/cube";
	import {
		useTimeStore
	} from "@/stores/time";
	import {
		useUserStore
	} from "@/stores/user";
	import Chart from '@/components/Echart.vue';
	import cube3d from '@/utils/cube3d.js'
	import { getToken } from '@/utils/auth.js'

	const cubeStore = useCubeStore();
	const timeStore = useTimeStore();
	const userStore = useUserStore();

	const vConsole = new VConsole()

	//是否有蓝牙权限
	const ble_has_permission = ref(false)
	//设备是否已连接
	const ble_is_connected = ref(false)
	//生成的打乱规则
	const cube_generate_scramble = ref('')
	// v3版本的数据
	const v3Data = ref('')
	//当前转动的字母代号
	const cubeMoves = ref([])
	// 设备信息
	const equipment = ref([])
	// 电池信息
	const battery = ref({})
	// 陀螺仪dataFour1数据
	const dataFour1 = ref([[], [], [], []])
	// 是否显示折线图
	const showLine = ref(false)
	// 当前飞机图
	const cubeFace = ref('')

	const times = ref(45);
	const moved = ref(false)

	let intervalTimer = undefined
	let watchCompleted = null
	let wait = 0
	let waitTime = 1000
	let cubeGame = null
	let startStepJson = ref({})
	let stopStepJson = ref({})
	
	
	// 接收的全部数据
	const json_data_receive_array = ref([])
	// 数据测试发送的数据
	const json_data_send = ref('')
	// 数据测试接收的数据
	const json_data_receive = ref('')
	// 数据测试的数据筛选类型
	const json_data_type = ref('')
	
	// 退出登录
	const handleLogout = async () => {
		try {
			await userStore.logout()
			uni.showToast({
				title: '已退出登录',
				icon: 'success'
			})
			
			// 跳转到登录页
			setTimeout(() => {
				uni.reLaunch({
					url: '/views/login'
				})
			}, 1500)
		} catch (error) {
			console.error('退出登录失败:', error)
			uni.showToast({
				title: '退出登录失败',
				icon: 'none'
			})
		}
	}

	// 跳转到登录页
	const goToLogin = () => {
		uni.navigateTo({
			url: '/views/login'
		})
	}

	// 跳转到Battle演示页面
	const goToBattleDemo = () => {
		uni.navigateTo({
			url: '/views/battle-demo'
		})
	}

	// 跳转到WebSocket测试页面
	const goToWebSocketExample = () => {
		uni.navigateTo({
			url: '/views/websocket-example'
		})
	}
	
	// 跳转到赛事查询页面
	const goToMatchQuery = () => {
		uni.navigateTo({
			url: '/views/match-query'
		})
	}

	// [调试] 从缓存中读取token
	const readTokenFromCache = () => {
		const cachedToken = getToken()
		console.log('[调试] 手动从缓存读取到的token:', cachedToken)
		uni.showModal({
			title: '缓存中的Token',
			content: cachedToken || '缓存中没有Token',
			showCancel: false
		})
	}

	const parseBoolean = pb => {
		return pb ? '是' : '否'
	}

	const log = (msg) => {
		console.log(JSON.stringify(msg))
	}

	const cubeGetFacelets = () => {
		mCall('cube_get_facelets')
	}

	const cubeSolveIn = () => {
		mCall('cube_solve_in')
	}

	// 蓝牙是否连接-与蓝牙交互
	const bleIsConnected = () => {
		mCall('ble_is_connected')
	}

	// 是否有蓝牙权限
	const bleHasPermission = () => {
		mCall('ble_has_permission')
	}

	// 打开蓝牙连接面板
	const bleShowScan = () => {
		mCall('ble_show_scan')
		
		equipment.value = []
		if (!equipment.value.length) {
			const inter = setInterval(() => {
				if (equipment.value.length) {
					// mCall('disable_gyroscope', 1)
					clearInterval(inter)
				} else {
					getEquipment()
					getBattery()
				}
			}, 5000)
		}
	}

	// 断开魔方连接
	const bleDisconnect = () => {
		mCall('ble_disconnect', '')
	}

	// 生成打乱规则
	const cubeGenerateScramble = () => {
		mCall('cube_generate_scramble')
	}

	// 魔方复原重置
	const cubeReset = () => {
		mCall('sendJSONData', {
			adress: '',
			data:{
				protoId: 6,
				step: 1,
				count: 28,
			}
		})
	
		
		cubeGame.cube.reset()
		
		
		mCall('sendJSONData', {
			adress: '',
			data:{
				protoId: 3,
				step: 1,
				count: 28,
			}
		})
	}
	
	// 同步魔方当前状态
	const cubeSync = () => {
		mCall('cube_sync')
	}

	// 开始游戏
	const beginGame = () => {
		mCall('cube_generate_scramble')
	}

	const start = () => {
		console.log('start')
		times.value = 45

		//重置比赛数据
		timeStore.reset();
		timeStore.startScramble(cube_generate_scramble.value);
		
		clearInterval(intervalTimer);
		intervalTimer = setInterval(() => {
			times.value--;
			if (times.value <= 0) {
				times.value = 0;
			}
			if (times.value <= 0) {
				clearInterval(intervalTimer);
				intervalTimer = undefined;
				onStopScramble();
			}
		}, 1000);
		
		mCall('keep_screen_on')
	}


	// 设备信息
	const getEquipment = () => {
		mCall('sendJSONData', {
			adress: '',
			data:{
				protoId: 3,
			}
		})
	}
	
	// 电池电量
	const getBattery = () => {
		mCall('sendJSONData', {
			adress: '',
			data:{
				protoId: 8,
			}
		})
	}
	
	
	// 发送数据
	const sendJSONData = () => {
		if (json_data_send.value) {
			const data = json_data_send.value
				.trim()
				.replace(/\r|\t|\n/g, '')
			try{
				mCall('sendJSONData', JSON.parse(data))
			}catch(e){
				log('请输入正确的JSON格式数据')
			}
			
		}
	}
	

	onMounted(() => {
		// test
		// const scramble = JSON.parse("{\"data\":\"B2 U^ L2 D B2 U R2 D2 F R^ B2 U2 B R B D B^ D^ U^\"}")
		// scramble.data = scramble.data.replace(/\^/g, '\'')
		// cube_generate_scramble.value = scramble.data
		// start()
		cubeGame = new cube3d()
		
		setInterval(() => {
			
		}, 2000)
		
		// var c = "R2 U' R2 U' R2 U2 B2 U R2 U' R2 U' B' F' U2 B' F".split(' ')
		// var test = function() {
		// 	setTimeout(() => {
		// 		if (c.length) {
		// 			cubeGame.transcube.trans(c[0])
		// 			c.shift()
		// 			test()
		// 		}
		// 	}, 17)
		// }
		// setTimeout(() => {
		// 	test()
		// }, 1000)
		

		mBus({
			ble_is_connected(res) {
				ble_is_connected.value = res.data
			},
			ble_has_permission(res) {
				ble_has_permission.value = res.data
			},
		
			// 接收转动魔方时的信息V2
			onReceiveJSONData(res) {
				res = res.data ? res.data : res
				if (res) {
					const resStr = JSON.stringify(res)
					
					if (+res.protoId === +json_data_type.value) {
						json_data_receive.value = resStr
						json_data_receive_array.value.push(resStr)
					}
					

					switch (+res.protoId) {
						// 转动
						case 1:
							log(res)
							const name = CubeMap[res.formula]
							res.cubeName = name
							
							cubeStore.onMove(res)
							v3Data.value = resStr
							cubeMoves.value.push(name)
							cubeGame.transcube.trans(name)
							
							VmCube.move(name)
							mCall('cube_get_facelets')
								
							break;
						// 设备信息
						case 3:
							log(res)
							equipment.value = [...equipment.value, res]
							break;
						// 电池电量
						case 4:
							battery.value = res
							break;
						// 账号绑定
						case 5:
							// accountMsg.value = resStr
							break;
						// 魔方复原重置
						case 6:
							// cubereset.value = resStr
							break;
						// 陀螺仪数据
						case 7:
							const now = Date.now()
							if (now - wait > waitTime) {
								// res.axisAngle1 && cubeStore.setGyroscopes(res.axisAngle1)
								wait = now
							}
							showLine.value = true
							if (res.dataFour1) {
								const arr = []
								dataFour1.value.forEach((v, i) => {
									v.push(res.dataFour1[i].value * (res.dataFour1[i].sign ? -1 : 1))
									v = v.slice(-150)
									arr.push(v)
								})
								dataFour1.value = JSON.parse(JSON.stringify(arr))
							}
							
							
							break;
						// 魔方操作公式历史-v1&v2&v3
						case 9:
							// cubehistory.value = resStr
							break;
						// 停表通知
						case 11:
							log('停表通知')
							log(res)
							if (timeStore.stage === 3) {
								onComplete();
								mCall('cube_get_facelets')
							}
						default:
							break;
					}

				}
			},
			cube_get_facelets(res) {
				console.log('cube_get_facelets', res)
				cubeStore.onFace(res.data)
				cubeGame.facelets.setFaceLets(res.data)
			},
			cube_solve_in(res) {
				console.log('cube_solve_in', res)
			},
			cube_is_solved(res) {
				console.log('cube_is_solved', res)
				cubeStore.onResolved(res.data)
			},

			cube_get_info(res) {
				// log(JSON.stringify(res))
			},
			sendJSONData(res) {
				// log(JSON.stringify(res))
			},
			cube_sync(res) {
				mCall('cube_get_facelets')
			}

			
			
		})
	})
	
	const clearHistory = () => {
		json_data_receive_array.value = []
	}
</script>

<style lang="scss" scoped>
	uni-button {
		margin: 0;
		margin-left: 30rpx;
	}

	.content {
		padding: 5%;
		counter-reset: list;
		background: transparent;
		min-height: 100vh;
	}

	// 用户头部样式
	.user-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		margin-bottom: 30rpx;
		background: rgba(255, 255, 255, 0.9);
		backdrop-filter: blur(10px);
		-webkit-backdrop-filter: blur(10px);
		border-radius: 12rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
		border-bottom: 1rpx solid rgba(238, 238, 238, 0.5);
		
		.user-info {
			display: flex;
			align-items: center;
			
			.avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 20rpx;
				border: 2rpx solid #eee;
			}
			
			.user-details {
				display: flex;
				flex-direction: column;
				
				.nickname {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 8rpx;
				}
				
				.phone {
					font-size: 24rpx;
					color: #666;
				}
			}
		}
		
		.logout-btn,
		.login-btn {
			height: 60rpx;
			padding: 0 30rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			border: none;
			
			&.logout-btn {
				background: #ff4757;
				color: #fff;
				
				&:active {
					background: #ff3742;
				}
			}
			
			&.login-btn {
				background: #667eea;
				color: #fff;
				
				&:active {
					background: #5a6fd8;
				}
			}
		}
	}

	.flex {
		display: flex;
		align-items: center;
	}

	.flexstart {
		justify-content: flex-start;
	}

	.card {
		margin: 20rpx 0;
		padding: 20rpx;
		background: rgba(255, 255, 255, 0.9);
		backdrop-filter: blur(10px);
		-webkit-backdrop-filter: blur(10px);
		border-radius: 12rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

		&:first-child {
			margin-top: 0;
		}

		button {
			height: 60rpx;
			line-height: 60rpx;
			font-size: 26rpx;
		}

		> .title {
			min-width: 280rpx;
			line-height: 1.4;
			font-size: 28rpx
		}
	}

	.game-rule {
		margin-bottom: 30rpx;

		.title {
			margin-bottom: 10rpx;
			color: #666;
			font-size: 24rpx;
		}
	}

	.log-box {
		height: 200rpx;

		.log-inner {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 200rpx;
			padding: 20rpx 30rpx;
			background: #fff;
			color: #666;
			line-height: 1.4;
			word-break: break-all;
			border: 1rpx solid #eee;
		}

		.log {
			height: 200rpx;
			padding: 10px;
			box-sizing: border-box;
			overflow-y: auto;
			word-break: break-all;

			p {
				margin: 5px 0;
			}
		}

		.clear {
			position: absolute;
			right: 80rpx;
			top: 10rpx;
			z-index: 2;
			width: 120rpx;
			height: 40rpx;
			font-size: 12px;
			line-height: 40rpx;
			opacity: 0.5;
		}
	}

	code {
		display: block;
		width: 80%;
		margin: 10rpx 0;
		padding: 20rpx;
		border-radius: 5px;
		background-color: #f5f5f5;
		font-size: 24rpx;
		word-break: break-word;
	}

	.start-game {
		margin: 50rpx 0;
	}

	.card uni-button.btn {
		display: block;
		height: 40px;
		width: 90%;
		margin: 8px;
		border-radius: 40px;
		line-height: 40px;
		font-size: 17px;
		border: 1px solid rgba(0, 0, 0, 0.2);

		&:after {
			border: none;
		}
	}

	.blank {
		margin-top: 50rpx;
	}
	
	.result {
		.msg {
			margin-top: 10rpx;
			color: #333;
		}
	}
	
	.led {
		margin: 10rpx;
	}
	
	.cube-box {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 200px;
		height: 200px;
		margin: 30px auto;
		background-color: #eee;
		border-radius: 10px;
		
		.cube {
			margin: 0;
		}
		
		.cube3d {
			width: 400px;
			height: 400px;
			transform: scale(0.5);
		}
	}
	.input-box {
		width: 80%;
		font-size: 24rpx;
		
		.label {
			margin-right: 20rpx;
		}
		
		.input {
			flex: 1;
			
			input {
				width: 100%;
			}
		}
	}
	
	code,
	textarea,
	input {
		display: block;
		width: 94%;
		margin: 10rpx 0;
		padding: 20rpx;
		border-radius: 5px;
		background-color: #f5f5f5;
		font-size: 24rpx;
		word-break: break-all;
	}
	
	.text-wrapper {
	  white-space: pre-wrap;
	}

	// Battle演示区域样式
	.battle-demo-section {
		margin-bottom: 30rpx;
		
		.battle-demo-btn {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			color: #fff;
			border: none;
			border-radius: 30rpx;
			padding: 0 40rpx;
			font-weight: bold;
			
			&:active {
				transform: scale(0.95);
			}
		}
	}

	// 赛事查询区域样式
	.match-query-section {
		margin-bottom: 30rpx;
		
		.match-query-btn {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			color: #fff;
			border: none;
			border-radius: 30rpx;
			padding: 0 40rpx;
			font-weight: bold;
			
			&:active {
				transform: scale(0.95);
			}
		}
	}

	// 调试区域样式
	.debug-section {
		margin-bottom: 30rpx;
		
		.debug-btn {
			background: #ff9f43;
			color: #fff;
			border: none;
			border-radius: 30rpx;
			padding: 0 40rpx;
			font-weight: bold;
			
			&:active {
				transform: scale(0.95);
			}
		}
	}
</style>